import rhythmdb, rb
import settings
from datetime import datetime
from pyscrobble.audioscrobbler import AudioScrobblerPost
from warnings import warn
if settings.debug:
	from log import log
	
VERSION = '0.1'

class LastRhythmPlugin(rb.Plugin):
	def __init__(self):
		rb.Plugin.__init__(self)

	def activate(self, shell):
		self.shell = shell
		self.current = None
		self.scrobbler = None
		self.addons = self.initAddons()
		self.addon = None
		self.change_signal = None
		self.date_played = None
		player = shell.get_player()
		player.connect('playing-uri-changed', self.loadAddon)
		
	def initAddons(self):
		'''
		TODO: provide addons support
		'''
		import addons.radio_hu as radio_hu
		addons = {}
		for uri in radio_hu.Radio_HU.uri:
			if settings.debug:
				log('Addon for %s initialized' % uri)
			addons[uri] = radio_hu.Radio_HU() 
		return addons

	def deactivate(self, shell):
		#self.song_change(shell.get_player(), '')
		if self.scrobbler:
			self.scrobbler.flushcache()
		if settings.debug:
			log(self.scrobbler.getlog(True))
			log("deactivating")

	def loadAddon(self, player, uri):
		'''
		Load the appropriate addon and initialize the signal
		Or "delete" the addon and the signal if there is no handler for the current path
		'''
		path = player.get_playing_path()
		
		if path == None or not self.addons.has_key(path):
			player.disconnect(self.change_signal)
			#self.song_change(player, '')
			self.scrobbler.flushcache()
			self.change_signal = None
			self.addon = None
			return
		
		self.addon = self.addons[path]
		self.scrobbler = AudioScrobblerPost(
							username=settings.username, 
							password=settings.password, 
							)
		if settings.debug:
			log('Addon for path %s loaded as %s' % (path, self.addon))
			
		if not self.change_signal:
			self.change_signal = player.connect('window_title_changed', self.song_change)

	def song_change(self, player, title):
		if not self.addon:
			return

		if self.date_played:
			length = datetime.now() - self.date_played
		else:
			length = 31 # pyscrobbler won't post a track less than 30 secs
		self.date_played = datetime.now()
		
		if self.current is not None and len(self.current) == 2:
			track = {
				'artist_name': self.current[0],
                'song_title': self.current[1],
                'length': length.seconds,
                'date_played': str(self.date_played)[:-7]
                }
			if settings.debug:
				log(track)
			self.scrobbler(**track)
		
		if settings.debug:
			log(title)
		self.current = self.addon(title)
		if settings.debug:
			log(self.current)
